//
//  KLineChartViewController.m
//  YKLineChartView
//
//  Created by wdecho on 16/4/12.
//  Copyright © 2015年 wdecho. All rights reserved.
//  http://git.oschina.net/wd123456
//

#import "KLineChartViewController.h"
#import "YKLineChart.h"
#import "AFNetworking.h"
#define MA5 5
#define MA10 10
#define MA20 20
@interface KLineChartViewController ()<YKLineChartViewDelegate>

@property(nonatomic ,strong) YKLineChartView *klineView;
@property (nonatomic ,strong) UIView *aview;
@property (nonatomic ,strong) NSMutableArray *dataArray;
@end

@implementation KLineChartViewController

-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
-(CGFloat)sumArrayWithData:(NSArray*)data andRange:(NSRange)range{
    CGFloat value = 0;
    if (data.count - range.location>range.length) {
        NSArray *newArray = [data objectsAtIndexes:[[NSIndexSet alloc] initWithIndexesInRange:range]];
        for (NSString *item in newArray) {
            NSArray *arr = [item componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@","]];
            value += [[arr objectAtIndex:4] floatValue];
        }
        if (value>0) {
            value = value / newArray.count;
        }
    }
    return value;
}

-(void)loadData:(NSString *)url{
    
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    
    sessionManager.requestSerializer = [AFHTTPRequestSerializer serializer];
    sessionManager.responseSerializer = [AFJSONResponseSerializer serializer];
    sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/x-javascript", @"text/html",nil];
    // 设置访问超时时间 （系统默认是60）
    sessionManager.requestSerializer.timeoutInterval = 30;
    
     NSMutableArray * array = [NSMutableArray array];
     [sessionManager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
         NSMutableArray *arraydata = responseObject;
         NSLog(@"%@",arraydata);
         NSLog(@"%ld",arraydata.count);
         for (int i=0; i<arraydata.count; i++) {
            NSDictionary *dic =arraydata[i];
            YKLineEntity * entity = [[YKLineEntity alloc]init];
            entity.high = [dic[@"High"] doubleValue];
            entity.open = [dic[@"Open"] doubleValue];
            
            entity.low = [dic[@"Low"] doubleValue];
            
            entity.close = [dic[@"Close"] doubleValue];
            entity.date = dic[@"DateStr"];
            
            //[self.dataArray addObject:dic[@"Close"]];
            
             double sumClose5 = 0;
             for (int j=0+i; j<MA5 + i  && i+MA5<arraydata.count; j++) {//MA5
                 NSDictionary *dic2 =arraydata[j];
                 sumClose5+= [dic2[@"Close"] doubleValue];
             }
             
             entity.ma5 = sumClose5/MA5;
             
            // 这三个要算啊
             double sumClose10 = 0;
             for (int j=0+i; j<MA10 + i  && i+MA10<arraydata.count; j++) {//MA10
                 NSDictionary *dic2 =arraydata[j];
                 sumClose10+= [dic2[@"Close"] doubleValue];
             }

             entity.ma10 = sumClose10 / MA10;
             
             
             double sumClose20 = 0;
             for (int j=0+i; j<MA20 + i  && i+MA20<arraydata.count; j++) {//MA10
                 NSDictionary *dic2 =arraydata[j];
                 sumClose20+= [dic2[@"Close"] doubleValue];
             }
             
             entity.ma20 = sumClose20 / MA20;
           // [item addObject:[NSNumber numberWithFloat:[self sumArrayWithData:self.dataArray andRange:NSMakeRange(1, MA5)]]];
            
           // NSLog(@"%@",item);
           // NSLog(@"%ld",item.count);
            
//            entity.ma10 = [dic[@"avg10"] doubleValue];
//            entity.ma20 = [dic[@"avg20"] doubleValue];
            
            
            entity.volume = [dic[@"Vol"] doubleValue];
            [array addObject:entity];

        }
         
        NSLog(@"数组%@",self.dataArray);
        
        [array addObjectsFromArray:array];
        YKLineDataSet * dataset = [[YKLineDataSet alloc]init];
        dataset.data = array;
        dataset.highlightLineColor = [UIColor colorWithRed:60/255.0 green:76/255.0 blue:109/255.0 alpha:1.0];
        dataset.highlightLineWidth = 0.7;
        dataset.candleRiseColor = [UIColor colorWithRed:233/255.0 green:47/255.0 blue:68/255.0 alpha:1.0];
        dataset.candleFallColor = [UIColor colorWithRed:33/255.0 green:179/255.0 blue:77/255.0 alpha:1.0];
        dataset.avgLineWidth = 1.f;
        dataset.avgMA10Color = [UIColor colorWithRed:252/255.0 green:85/255.0 blue:198/255.0 alpha:1.0];
        dataset.avgMA5Color = [UIColor colorWithRed:67/255.0 green:85/255.0 blue:109/255.0 alpha:1.0];
        dataset.avgMA20Color = [UIColor colorWithRed:216/255.0 green:192/255.0 blue:44/255.0 alpha:1.0];
        dataset.candleTopBottmLineWidth = 1;
        
        self.klineView = [[YKLineChartView alloc]init];
        
       self.klineView.frame = CGRectMake(0, 100, self.view.frame.size.width, 240);
        //[self.klineView setupChartOffsetWithLeft:50 top:100 right:50 bottom:10];
        UIView *aView =[[UIView alloc]initWithFrame:CGRectMake(0, 200, self.view.frame.size.width, 400)];
        aView.backgroundColor =[UIColor cyanColor];
        [self.view addSubview:aView];
        [aView addSubview:self.klineView];
        self.klineView.gridBackgroundColor = [UIColor whiteColor];
        self.klineView.borderColor = [UIColor colorWithRed:203/255.0 green:215/255.0 blue:224/255.0 alpha:1.0];
        self.klineView.borderWidth = .5;
        self.klineView.candleWidth = 8;
        self.klineView.candleMaxWidth = 30;
        self.klineView.candleMinWidth = 1;
        self.klineView.uperChartHeightScale = 0.7;
        self.klineView.xAxisHeitht = 25;
        self.klineView.delegate = self;
        self.klineView.highlightLineShowEnabled = YES;
        self.klineView.zoomEnabled = YES;
        self.klineView.scrollEnabled = YES;
        [self.klineView setupData:dataset];
    
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];

}
- (void)viewDidLoad {
    [super viewDidLoad];

    [self loadData:@"http://abiao123.xicp.net/LHWeb/Api/GetKLineData?code=002709.SZ&staDate=2015-1-1&endDate=2016-5-29&type=1"];
//    NSMutableArray *item = [NSMutableArray array];
//
//     [item addObject:[NSNumber numberWithFloat:[self sumArrayWithData:self.dataArray andRange:NSMakeRange(1, MA5)]]];
//    NSLog(@"%@",item);
    

    
    // Do any additional setup after loading the view.
    
//    NSString * path =[[NSBundle mainBundle]pathForResource:@"data.plist" ofType:nil];
//    NSArray * sourceArray = [[NSDictionary dictionaryWithContentsOfFile:path] objectForKey:@"data"];
//    NSMutableArray * array = [NSMutableArray array];
//    for (NSDictionary * dic in sourceArray) {
//        
//        YKLineEntity * entity = [[YKLineEntity alloc]init];
//        entity.high = [dic[@"high_px"] doubleValue];
//        entity.open = [dic[@"open_px"] doubleValue];
//        
//        entity.low = [dic[@"low_px"] doubleValue];
//        
//        entity.close = [dic[@"close_px"] doubleValue];
//        
//        entity.date = dic[@"date"];
//        entity.ma5 = [dic[@"avg5"] doubleValue];
//        entity.ma10 = [dic[@"avg10"] doubleValue];
//        entity.ma20 = [dic[@"avg20"] doubleValue];
//        entity.volume = [dic[@"total_volume_trade"] doubleValue];
//        [array addObject:entity];
//        //YTimeLineEntity * entity = [[YTimeLineEntity alloc]init];
//    }
//    [array addObjectsFromArray:array];
//    YKLineDataSet * dataset = [[YKLineDataSet alloc]init];
//    dataset.data = array;
//    dataset.highlightLineColor = [UIColor colorWithRed:60/255.0 green:76/255.0 blue:109/255.0 alpha:1.0];
//    dataset.highlightLineWidth = 0.7;
//    dataset.candleRiseColor = [UIColor colorWithRed:233/255.0 green:47/255.0 blue:68/255.0 alpha:1.0];
//    dataset.candleFallColor = [UIColor colorWithRed:33/255.0 green:179/255.0 blue:77/255.0 alpha:1.0];
//    dataset.avgLineWidth = 1.f;
//    dataset.avgMA10Color = [UIColor colorWithRed:252/255.0 green:85/255.0 blue:198/255.0 alpha:1.0];
//    dataset.avgMA5Color = [UIColor colorWithRed:67/255.0 green:85/255.0 blue:109/255.0 alpha:1.0];
//    dataset.avgMA20Color = [UIColor colorWithRed:216/255.0 green:192/255.0 blue:44/255.0 alpha:1.0];
//    dataset.candleTopBottmLineWidth = 1;
//    
//    [self.klineView setupChartOffsetWithLeft:50 top:100 right:50 bottom:10];
//    self.klineView.gridBackgroundColor = [UIColor whiteColor];
//    self.klineView.borderColor = [UIColor colorWithRed:203/255.0 green:215/255.0 blue:224/255.0 alpha:1.0];
//    self.klineView.borderWidth = .5;
//    self.klineView.candleWidth = 8;
//    self.klineView.candleMaxWidth = 30;
//    self.klineView.candleMinWidth = 1;
//    self.klineView.uperChartHeightScale = 0.7;
//    self.klineView.xAxisHeitht = 25;
//    self.klineView.delegate = self;
//    self.klineView.highlightLineShowEnabled = YES;
//    self.klineView.zoomEnabled = YES;
//    self.klineView.scrollEnabled = YES;
//    [self.klineView setupData:dataset];
}

-(void)chartValueSelected:(YKViewBase *)chartView entry:(id)entry entryIndex:(NSInteger)entryIndex
{
    
}

- (void)chartValueNothingSelected:(YKViewBase *)chartView
{
}

- (void)chartKlineScrollLeft:(YKViewBase *)chartView
{
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
